package com.huaxin.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaxin.device.common.MyMetaObjectHandler;
import com.huaxin.device.dto.request.AddDeviceModelReqDTO;
import com.huaxin.device.dto.request.UpdateDeviceModelReqDTO;
import com.huaxin.device.mapper.DeviceModelMapper;
import com.huaxin.device.mapping.DeviceModelMapping;
import com.huaxin.device.models.DeviceModel;
import com.huaxin.device.service.DeviceModelService;
import com.huaxin.hxjwt.entity.ResponseCode;
import com.huaxin.hxjwt.entity.ResponseResult;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class DeviceModelServiceImpl extends ServiceImpl<DeviceModelMapper, DeviceModel> implements DeviceModelService {
    private final ApplicationContext applicationContext;
    private final CacheManager cacheManager;
    private final MyMetaObjectHandler myMetaObjectHandler;
    private final DeviceModelMapping deviceModelMapping;

    /**
     * 添加设备型号
     *
     * @param in
     * @return
     */
    @Override
    public ResponseResult<String> addDeviceModel(AddDeviceModelReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数错误");
        }
        if (StringUtils.isBlank(in.getModelCode())) {
            return ResponseResult.parameterError(null, "设备型号编码不能为空");
        }
        if (this.existsByFields(DeviceModel::getModelCode, in.getModelCode(), null)) {
            return ResponseResult.parameterError(null, "设备型号编码已存在");
        }
        if (StringUtils.isBlank(in.getDeviceType())) {
            return ResponseResult.parameterError(null, "设备类型不能为空");
        }
        if (StringUtils.isBlank(in.getDeviceNameTemplate())) {
            return ResponseResult.parameterError(null, "设备默认命名模板不能为空");
        }
        DeviceModel deviceModel = deviceModelMapping.toEntity(in);
        if (this.save(deviceModel)) {
            return ResponseResult.ok("添加设备型号成功！");
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "添加失败，请稍后再试！", null);
        }
    }

    /**
     * 删除设备型号
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult<String> deleteDeviceModel(String id) {
        if (StringUtils.isBlank(id)) {
            return ResponseResult.parameterError(null, "设备型号ID不能为空");
        }
        if (applicationContext.getBean(DeviceModelService.class).removeById(id)) {
            return ResponseResult.ok(null);
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "删除设备型号失败！", null);
        }
    }

    /**
     * 修改设备型号
     *
     * @param in
     * @return
     */
    @Override
    public ResponseResult<String> updateDeviceModel(UpdateDeviceModelReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数错误");
        }
        if (StringUtils.isBlank(in.getId())) {
            return ResponseResult.parameterError(null, "设备型号ID不能为空");
        }
        if (StringUtils.isBlank(in.getDeviceNameTemplate())) {
            return ResponseResult.parameterError(null, "设备默认命名模板不能为空");
        }
        DeviceModel deviceModel = this.getById(in.getId());
        deviceModelMapping.updateEntity(in, deviceModel);
        if (this.updateById(deviceModel)) {
            return ResponseResult.ok(null);
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "修改设备型号失败，请稍后再试！", null);
        }
    }

    /**
     * 获取设备型号列表
     *
     * @param pageNum    页码
     * @param pageSize   每页数量
     * @param modelCode  设备型号编码
     * @param deviceType 设备类型
     * @return
     */
    @Override
    public ResponseResult<Page<DeviceModel>> getDeviceModelList(Integer pageNum, Integer pageSize, String modelCode, String deviceType) {
        Page<DeviceModel> page = new Page<>(pageNum, pageSize);
        QueryWrapper<DeviceModel> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(modelCode)) {
            wrapper.like("model_code", modelCode);
        }
        if (StringUtils.isNotBlank(deviceType)) {
            wrapper.like("device_type", deviceType);
        }
        return ResponseResult.ok(this.page(page, wrapper));
    }

    /**
     * 获取设备型号详情
     *
     * @param id 设备型号ID
     * @return
     */
    @Override
    public DeviceModel getDeviceModelDetail(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        return this.getById(id);
    }

    /**
     * 检查多个字段值组合是否已存在（排除当前ID）
     *
     * @param fieldGetter 字段Getter
     * @param fieldValue  字段值
     * @param excludeId   要排除的ID（可为null）
     * @return 是否存在匹配记录
     */
    private boolean existsByFields(
            SFunction<DeviceModel, ?> fieldGetter,
            Object fieldValue,
            String excludeId) {

        if (fieldGetter == null) return false;

        LambdaQueryWrapper<DeviceModel> wrapper = new LambdaQueryWrapper<>();

        if (fieldValue == null ||
                (fieldValue instanceof CharSequence cs && cs.toString().trim().isEmpty())) {
            wrapper.and(wrapper1 -> wrapper1
                    .isNull(fieldGetter)
                    .or().eq(fieldGetter, "")
            );
        } else {
            wrapper.eq(fieldGetter, fieldValue.toString().trim());
        }

        if (excludeId != null && !excludeId.trim().isEmpty()) {
            wrapper.ne(DeviceModel::getId, excludeId.trim());
        }

        return this.count(wrapper) > 0;
    }
}
